package www.golf.web.session;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

import org.postgresql.jdbc4.Jdbc4Array;
import org.zkoss.util.media.AMedia;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zul.SimpleTreeNode;
import org.zkoss.zul.Window;
import org.zkoss.zul.api.Listbox;

import www.golf.ibatis.IBatisFactory;
import www.golf.web.util.UtilZKObject;

import com.ibatis.sqlmap.client.SqlMapClient;

public class WebSession extends Window{
	public static int add=1;
	public static int edit=2;
	public static String jasper_home="jasper/";
   public Session getSession(){
	   return getDesktop().getSession();
   }
   public boolean conditionLoginSession(){
	   if(getSession().getAttribute("isLogin")==null){
		   Executions.getCurrent().sendRedirect("../index.zul");
		   return false;
	   }
	   return true;
   }
   public String getReal_Path(){
	   return ((ServletContext)Executions.getCurrent().getDesktop()
			   .getWebApp().getNativeContext()).getRealPath("/");
   }
  
   public Integer getUserPid(){
	   return (Integer)getLoginUserAttribute("pid");
   }
   public int[] getUserGroup(){
	   int i[]={};
	   try {
		   return (int[])getLoginUserAttribute("group");
	   } catch (Exception e) {
		   return i;
	   }
	   
   }
   public int[] getUserJob(){
	   return (int[])getLoginUserAttribute("job");
   }
   public Integer getUserPower(){
	   return (Integer)getLoginUserAttribute("power");
   }
   public int[] setJdbc4Array(Jdbc4Array array){
	   int[] k = null;
	   try {
		   ResultSet rs=array.getResultSet();
		   rs.last();
		   k=new int[rs.getRow()];
		   rs.beforeFirst();
		   while(rs.next()){
			   k[rs.getInt(1)-1]=rs.getInt(2);
		   }
	   } catch (SQLException e) {
		   e.printStackTrace();
	   }
	   return k;
   }
   /**
    * 取得使用者相關資訊
    * @param type-"user""pwd""pid""job""group""powers"
    * @return value
    */
   public Object getLoginUserAttribute(String type){
	   return (Object) ((getSession().getAttribute(type)==null)?0:getSession().getAttribute(type));
   }
   public void setLoginSession(String user,String pass,Integer pid,Array job,Array group,Integer power){
	   getSession().setAttribute("user",user);
	   getSession().setAttribute("pwd",pass);
	   getSession().setAttribute("pid",pid);
	   getSession().setAttribute("job",setJdbc4Array((Jdbc4Array)job));
	   getSession().setAttribute("group",setJdbc4Array((Jdbc4Array)group));
	   getSession().setAttribute("power",power);
	   getSession().setAttribute("isLogin",true);
   }
   public Component getm_content(){
	   return Executions.getCurrent().getDesktop().getPage("main_content").getFellow("main")
		.getFellow("m_content");
   }
   public void setPagefileSession(String path){
	   getSession().setAttribute("pagefile",path);
   }
   public String getPagefileSession(){
	   return  (String) getSession().getAttribute("pagefile");
   }
   public SqlMapClient dbSession(){
		return IBatisFactory.getInstance().getSqlSession();
   }
   public void dbSessionClose(){
		IBatisFactory.getInstance().getSqlSession().openSession().close();
   }
   public void setList(Window win,String SQL,String Fellow_id){
	   setList(win,SQL,Fellow_id,null);
	}
   public void setList(Window win,String SQL,String Fellow_id,Object SQL_value){
		try {
			List type=SQL_value==null?dbSession().queryForList(SQL)
								 :dbSession().queryForList(SQL,SQL_value);
			Listbox listbox=(Listbox) win.getFellow(Fellow_id);
			if(listbox.getChildren().size()>1){
				UtilZKObject.clearObjectValue(win.getFellow(Fellow_id));
				listbox.appendItemApi("请选择", null);
			}else if(listbox.getChildren().size()==0){
				listbox.appendItemApi("请选择", null);
			}
			for(Object obj:type){
				Map map=((HashMap)obj);
				listbox.appendItemApi(String.valueOf(map.get("label")), String.valueOf(map.get("value")));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
   public SimpleTreeNode setTreeNode(String basic_value,List<Map> data){
		
		//		follow this result
		//		   pid  |  name  |  parent
		//		----------------------------
		SimpleTreeNode node=null;
		ArrayList<SimpleTreeNode> list = new ArrayList<SimpleTreeNode>();
		Iterator it=data.iterator();
		while(it.hasNext()){
			Map m = (Map) it.next();
			if(m.get("parent").equals(basic_value)){
				SimpleTreeNode subList = getTreeList(m,data);
				list.add(subList);
			}
		}
		node = new SimpleTreeNode(null, list);
		return node;
	}
	public SimpleTreeNode getTreeList(Map node,List<Map> list){
		
		ArrayList<SimpleTreeNode> sub_list = new ArrayList<SimpleTreeNode>();
		Iterator it=list.iterator();
		while (it.hasNext()){
			Map m = (Map) it.next();
			if (m.get("parent").equals(node.get("pid"))) {
				SimpleTreeNode stn = getTreeList(m,list);
				sub_list.add(stn);
			}
		}
		SimpleTreeNode stn = new SimpleTreeNode(node, sub_list);
		return stn;
	}
	/**
	 * pdf 汇出
	 * @param jrxml jrxml名称
	 * @param map parameter值
	 * @param field 对象值
	 * @param PDF_name PDF名称
	 */
	public void createPDF(String jrxml,Map map,Map field,String PDF_name){
		try {
			String SQL="select ";
			Iterator it=field.keySet().iterator();
			while(it.hasNext()){
				String ket_name =(String)it.next();
				SQL+="'"+field.get(ket_name)+"' as "+ket_name+",";
			}
			SQL+="'end' as end";
			ResultSet resultSet = null;
			java.sql.Connection con =dbSession().getDataSource().getConnection();
			PreparedStatement statement;
			statement = con.prepareStatement(SQL);
			resultSet = statement.executeQuery(); 
			JRResultSetDataSource result = new JRResultSetDataSource( resultSet );   
			ByteArrayOutputStream os=new ByteArrayOutputStream();  
			JasperReport jasperReport = JasperCompileManager.compileReport(getReal_Path()+jasper_home+jrxml+".jrxml");    
			JasperPrint jasperPrint =  JasperFillManager.fillReport( jasperReport, map, result); 
			JasperExportManager.exportReportToPdfStream(jasperPrint, os);
			InputStream is = new ByteArrayInputStream(os.toByteArray());  
			AMedia amedia =new AMedia(PDF_name, "pdf", "application/pdf", is);
			getDesktop().getSession().setAttribute("jasper", amedia);
			getDesktop().getExecution().sendRedirect("/jasper/jasper.zul", "_blank");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
